package com.qd.panda.gas.station.ejiayou.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qd.panda.gas.station.ejiayou.util.EGasSignUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 易加油状态推送
 */
@RequestMapping("/sys/payOrder")
@RestController
@Validated
@Slf4j
@RequiredArgsConstructor
public class EPayNotifyController {
    private final ObjectMapper objectMapper;
    private final HttpServletResponse response;

    private static final String RETURN_SUCCESS = "SUCCESS";
    private static final String RETURN_ERROR = "ERROR";

    /**
     * 接收易加油状态报告
     *
     * @param jsonNode 参数
     * @return success fail
     */
    @PostMapping(value = "/eGasNotify")
    public ResponseEntity<Void> eGasNotify(@RequestBody(required = false) JsonNode jsonNode) {
        if(null!=jsonNode){
            log.info("接收易加油推送的回执信息: {}",jsonNode.toPrettyString());
            JsonNode signNode = jsonNode.get("sign");
            if (null != signNode) {
                try {
                    String sign = signNode.asText();
                    Map<String, Object> param = new ObjectMapper().readValue(jsonNode.toString(), new TypeReference<>() {
                    });
                    param.remove("sign");
                    String sign1 = EGasSignUtil.sign(param);
                    log.info("接收易加油推送的回执信息,原始签名:{},自己签名: {},签名比对: {}", sign, sign1, (sign.equalsIgnoreCase(sign1)));
                } catch (Exception ignored) {

                }
            }
        }
        renderText();
        return null;
    }


    private void renderText() {
        renderText(RETURN_SUCCESS);
    }

    private void renderText(String text) {
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("returnCode", text);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset:utf-8;");
        try (PrintWriter out = response.getWriter()) {
            out.append(objectNode.toString());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
